type
<template>
  <div class="login-page">
    <h5>登录者也</h5>

    <ValidateForm @form-submit="onFormSubmit">
      <div class="form-item">
        <label class="form-label">邮箱地址</label>
        <ValidateInput
          v-model="emailVal"
          :rules="eamilRules"
          type="text"
          placeholder="请输入邮箱地址"
        ></ValidateInput>
      </div>

      <div class="form-item">
        <label class="form-label">密码</label>
        <ValidateInput
          v-model="passwordVal"
          :rules="passwordRules"
          type="password"
          placeholder="请输入密码"
        ></ValidateInput>
      </div>

      <template #submit>
        <button type="submit" class="btn btn-primary">登录</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import ValidateForm from "../components/ValidateForm.vue";
import ValidateInput, { type RulesProp } from "../components/ValidateInput.vue";
import createMessage from "../components/createMessage";
import { useUserStore } from "../store/user";

const router = useRouter();
const userStore = useUserStore();

const emailVal = ref("");
const eamilRules: RulesProp = [
  { type: "required", message: "邮箱地址不能为空" },
  { type: "email", message: "请输入正确的电子邮箱格式" },
];

const passwordVal = ref("");
const passwordRules: RulesProp = [
  { type: "required", message: "密码不能为空" },
];

const onFormSubmit = async (result: boolean) => {
  if (result) {
    try {
      await userStore.login(emailVal.value, passwordVal.value);
      await userStore.fetchCurrentUser();
      createMessage("登录成功，2秒后跳转首页", "success", 2000);

      setTimeout(() => {
        router.push("/");
      }, 2000);
    } catch (e) {
      console.log("Login Page:", e);
    }
  }
};
</script>

<style scoped>
.login-page {
  width: 330px;
  margin: 0 auto;
  padding: 16px;

  h5 {
    margin: 24px 0;
    font-weight: normal;
    font-size: 20px;
  }

  .form-item {
    margin-bottom: 16px;
    text-align: left;

    .form-label {
      display: block;
      margin-bottom: 8px;
    }
  }
}
</style>
